import type { WriteStream } from 'node:fs';
import path from 'node:path';
import { TEMP_DIR } from '@/server/utils/constants';
import { FILE_SIZE } from '@/utils/constants';
import fse from 'fs-extra';
import { defineEventHandler, readBody } from 'h3';

export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  // 1. 获取切片文件的存放路径
  const chunkDir = path.resolve(TEMP_DIR, `chunkDir_${body.filename}`);

  // 2. 读取切片文件目录
  const chunks = fse.readdirSync(chunkDir);

  // 3. 按切片文件名下标排序
  chunks.sort(
    (a: string, b: string) => Number(a.split('-')[1]) - Number(b.split('-')[1]),
  );

  // 4. 合并切片文件
  await mergeFileChunks(chunkDir, chunks, `${body.fileHash}.${body.ext}`);

  // 5. 删除存放切片的文件目录
  await fse.rm(chunkDir, { recursive: true });

  return {
    errno: 0,
    msg: `文件 ${body.filename} 上传成功`,
  };
});

async function mergeFileChunks(
  chunkFilePath: string,
  chunks: string[],
  filename: string,
) {
  await Promise.all(
    chunks.map((chunk: string, index: number) =>
      pipeStream(
        path.resolve(chunkFilePath, chunk),
        fse.createWriteStream(path.resolve(TEMP_DIR, filename), {
          start: index * FILE_SIZE,
        }),
      ),
    ),
  );
}

function pipeStream(path: string, writeStream: WriteStream) {
  return new Promise((resolve) => {
    const readStream = fse.createReadStream(path);

    readStream.on('end', () => {
      fse.unlinkSync(path);
      resolve(true);
    });

    readStream.pipe(writeStream);
  });
}
